package com.ys.common.exception;

import com.ys.common.result.GlobalException;
import com.ys.common.result.Result;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(GlobalException.class)
    public Result<?> handleException(Exception e) {
        return Result.fail(500, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleOtherException(Exception ex) {
        // 可根据需要打印日志
        return Result.fail(500, "系统异常: " + ex.getMessage());
    }

    // 捕获 MethodArgumentNotValidException 异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMessage.append(fieldError.getField())
                    .append(": ")
                    .append(fieldError.getDefaultMessage())
                    .append("; ");
        });
        return Result.fail(400, errorMessage.toString());
    }

}